﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.ObjectModel;
using System.Windows;
using TransControlSystem.Dao;
using TransControlSystem.Model;
using TransControlSystem.Utils;
using TransControlSystem.ViewModel.Common.Command;

namespace TransControlSystem.ViewModel.Common
{
    /// <summary>
    /// ViewModel of CreateUserWindow 创建用户的ViewModel
    /// <author>作者：徐一贺</author>  
    /// </summary>
    public class CreateUserViewModel : ViewModelBase
    {
        /// <summary>
        /// 隐藏窗体命令
        /// <author>作者：徐一贺</author>  
        /// </summary>
        public DelegateCommand HideCreateUserWindowCommand { get; set; }

        /// <summary>
        /// 保存用户
        /// <author>作者：徐一贺</author>  
        /// </summary>
        public DelegateCommand SaveUserCommand { get; set; }

        //用户信息
        private User _UserIfo = new User();
        /// <summary>
        /// 用户信息
        /// <author>作者：徐一贺</author>  
        /// </summary>
        public User UserIfo
        {
            get
            {
                return _UserIfo;
            }
            set
            {
                _UserIfo = value;
                RaisePropertyChanged("UserIfo");
            }
        }
        /// <summary>
        /// 下拉框列表
        /// <author>作者：徐一贺</author>  
        /// </summary>
        private ObservableCollection<User> _ComBoxItems;
        public ObservableCollection<User> ComBoxItems
        {
            get
            {
                return _ComBoxItems;
            }
            set
            {
                _ComBoxItems = value;
                RaisePropertyChanged("ComBoxItems");
            }
        }

        /// <summary>
        /// 下拉框当前选中
        /// <author>作者：徐一贺</author>  
        /// </summary>
        private User _CurrentlySelectedItem;
        public User CurrentlySelectedItem
        {
            get
            {
                return _CurrentlySelectedItem;
            }
            set
            {
                _CurrentlySelectedItem = value;
                RaisePropertyChanged("CurrentlySelectedItem");
            }
        }



        /// <summary>
        /// Constructors 构造方法
        /// <author>作者：徐一贺</author>  
        /// </summary>
        public CreateUserViewModel()
        {
            //初始化下拉框
            ComBoxItems = new ObservableCollection<User>();
            User user = new User();
            user.Role = "system";
            ComBoxItems.Add(user);
            user = new User();
            user.Role = "guest";
            ComBoxItems.Add(user);
            //初始化隐藏窗体委托
            HideCreateUserWindowCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(HideCreateUserWindowHandler)
            };
            //初始化保存委托
            SaveUserCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(SaveUserWindowHandler)
            };
        }
        /// <summary>
        /// 保存处理程序
        /// <author>作者：徐一贺</author>  
        /// </summary>
        /// <param name="obj">参数</param>
        private void SaveUserWindowHandler(object obj)
        {
            try
            {
                if (UserIfo.Account == null || UserIfo.Account.Trim() == "")
                {
                    //警告 必须填写账号
                    WindowManager.ShowWarning("警告", "尊敬的用户，请您填写账号。");
                    return;
                }
                else if (UserIfo.Account.Trim().Length > 20)
                {
                    //警告 账号不要超过20个字符
                    WindowManager.ShowWarning("警告", "尊敬的用户，请您填写账号不要超过20个字符。");
                    return;
                }
                else if (XyhUtils.IsHasSQLInject(UserIfo.Account))
                {
                    WindowManager.ShowWarning("警告", "账号不可用包含SQL注入关键词！");
                    return;
                }
                if (UserIfo.UserName == null || UserIfo.UserName.Trim() == "")
                {
                    //警告 必须填写用户名
                    WindowManager.ShowWarning("警告", "尊敬的用户，请您填写用户名。");
                    return;
                }
                if (UserIfo.Password == null || UserIfo.Password.Trim() == "")
                {
                    //警告 必须填写密码
                    WindowManager.ShowWarning("警告", "尊敬的用户，请您填写密码。");
                    return;
                }
                else if (UserIfo.Password.Trim().Length < 6)
                {
                    //警告 密码至少6位
                    WindowManager.ShowWarning("警告", "尊敬的用户，请您填写至少六位密码。");
                    return;
                }
                else if (UserIfo.Password.Trim().Length > 20)
                {
                    //警告 密码不可超过20位
                    WindowManager.ShowWarning("警告", "尊敬的用户，请您填写的密码不可超过20位。");
                    return;
                }
                else if (XyhUtils.IsHasSQLInject(XyhUtils.Encrypt(UserIfo.Password)))
                {
                    WindowManager.ShowWarning("警告", "密码不可用包含SQL注入关键词！");
                    return;
                }
                if (CurrentlySelectedItem == null)
                {
                    //警告 必须选择角色
                    WindowManager.ShowWarning("警告", "尊敬的用户，请您必须选择角色。");
                    return;
                }


                UserIfo.Role = CurrentlySelectedItem.Role;

                string CheckAccountExistsSql = @"select * from [User] where Account = @Account";
                User CheckAccountExists = DapperTools.Query<User>(CheckAccountExistsSql, UserIfo);
                if (CheckAccountExists != null)
                {
                    //警告 账号不可重复
                    WindowManager.ShowWarning("警告", "尊敬的用户，请您输入的账号已存在，请修改后再次保存。");
                    return;
                }
                string CheckUserNameExistsSql = @"select * from [User] where UserName = @UserName";
                User CheckUserNameExists = DapperTools.Query<User>(CheckUserNameExistsSql, UserIfo);
                if (CheckUserNameExists != null)
                {
                    //警告 用户名不可重复
                    WindowManager.ShowWarning("警告", "尊敬的用户，请您输入的用户名已存在，请修改后再次保存。");
                    return;
                }
                UserIfo.Password = XyhUtils.Encrypt(UserIfo.Password);
                string sql = @"insert [User] (
                                    Account,
                                    UserName,
                                    Password,
                                    Role
                                    ) 
                                    values(
                                    @Account,
                                    @UserName,
                                    @Password,
                                    @Role
                                    )";

                int result = DapperTools.Add<User>(sql, UserIfo);
                if (result > 0)
                {
                    LogTool.SaveLog("账号权限管理-创建用户", "创建了账号为【" + UserIfo.Account + "】,用户名为【" + UserIfo.UserName + "】,角色为【" + UserIfo.RoleName + "】的用户。");
                    Application.Current.Dispatcher.Invoke((Action)delegate ()
                    {
                        UserIfo = new User();
                    });
                    Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "ReLoadUserQueue"));
                    Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "HideCreateUserWindow"));
                }
            }
            catch (Exception e)
            {
                LogTool.SaveSysLog(e.Message, "创建新用户异常");
            }
        }


        /// <summary>
        /// 隐藏本窗体处理程序
        /// <author>作者：徐一贺</author>  
        /// </summary>
        /// <param name="obj">参数</param>
        private void HideCreateUserWindowHandler(object obj)
        {
            Application.Current.Dispatcher.Invoke((Action)delegate ()
            {
                UserIfo = new User();
            });
            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "HideCreateUserWindow"));
        }
    }
}
